package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;

/**
 * @author: WangYaWei
 * @description:
 * @create: 2019-08-15 14:18
 **/
@Service
public class SpitService {

    @Autowired
    private MongoTemplate mongoTemplatel;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SpitDao spitDao;

    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    public Spit findById(String id) {
        return spitDao.findById(id).get();
    }

    public void update(Spit spit) {
        spitDao.save(spit);
    }

    /**
     * 发布吐槽活评论
     * @param spit
     */
    public void add(Spit spit) {
        spit.setId(idWorker.nextId() + "");
        spit.setVisits(0);
        spit.setShare(0);
        spit.setComment(0);
        spit.setThumbup(0);
        spit.setState("1");
        spitDao.save(spit);

        if(spit.getParentid() != null && !"".equals(spit.getParentid())){
            mongoTemplatel.updateFirst(
                    Query.query(Criteria.where("id").is(spit.getParentid())),
                    new Update().inc("comment", 1),
                    spit.getClass()
            );
        }
    }

    public void deleteById(String id) {
        spitDao.deleteById(id);
    }

    public Page<Spit> findByParentid(String parentId, int page, int size) {
        return spitDao.findByParentid(parentId, PageRequest.of(page - 1, size));
    }


    public void updateThumbup(String id) {
        Query query = Query.query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplatel.updateFirst(query, update, Spit.class);
    }

    public void updateVisits(String id) {
        mongoTemplatel.updateFirst(
                Query.query(Criteria.where("id").is(id)),
                new Update().inc("visits", 1),
                Spit.class
        );
    }

    public void updateShare(String id) {
        mongoTemplatel.updateFirst(
                Query.query(Criteria.where("id").is(id)),
                new Update().inc("share", 1),
                Spit.class
        );
    }
}
